package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
)

// 获取管理员角色信息
func GetUserAdminRoleInfo(p map[string]interface{}) *models.UserAdminRole {
	o := orm.NewOrm()
	userAdminRole := &models.UserAdminRole{}
	qs := o.QueryTable("UserAdminRole")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(userAdminRole)
	return userAdminRole
}

// 添加管理员角色信息
func AddUserAdminRole(input url.Values) (int64, error) {
	o := orm.NewOrm()
	userAdminRole := &models.UserAdminRole{}
	school := &models.School{}
	if _, ok := input["school_id"]; ok {
		school.Id = utils.Atoi64(input["school_id"][0])
		o.Read(school)
	}
	userAdminRole.School = school
	if _, ok := input["name"]; ok {
		userAdminRole.Name = input["name"][0]
	}
	if _, ok := input["describe"]; ok {
		userAdminRole.Describe = input["describe"][0]
	}
	return o.Insert(userAdminRole)
}

// 修改管理员角色信息
func EditUserAdminRole(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" || k == "authority_id" {
			continue
		}
		if k == "school_id" {
			p[k] = utils.Atoi64(v[0])
		} else {
			p[k] = v[0]
		}
	}
	return o.QueryTable("UserAdminRole").Filter("id", input["id"][0]).Update(p)
}

// 获取管理员角色列表
func GetUserAdminRoleList(p map[string]interface{}) (int64, []*models.UserAdminRole) {
	var userAdminRoleList []*models.UserAdminRole
	o := orm.NewOrm()
	qs := o.QueryTable("UserAdminRole")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["excludeSuper"]; ok {
		qs = qs.Filter("id__gt", 1)
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&userAdminRoleList)
	return totalCount, userAdminRoleList
}